/**
 * 用户获取接口测试用例
 *
 * Created by snowingsea on 2020/02/02.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const { statusKind } = require('./../../../../phoenix/models/users');

module.exports = describe('/GET users/:id.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let user = {};
  function url(userId) {
    if (!userId) userId = user.userId;
    return `/users/${userId}.json`;
  }
  before(function (done) {
    administrator.createRandomUser()
      .then((res) => {
        user = res;
        newUserIds.push(user.userId);
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.administrator(uri, url, 'get');

  // 正常请求
  it('it should GET a user', function (done) {
    administrator.login()
      .then(() => {
        chai.request(uri)
          .get(url())
          .set('Authorization', `Bearer ${administrator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.userMessage(res.body);
            res.body.userId.should.be.eql(user.userId);
            res.body.username.should.be.eql(user.username);
            res.body.nickname.should.be.eql(user.nickname);
            res.body.role.should.be.eql(user.role);
            res.body.lang.should.be.eql(user.lang);
            res.body.status.should.be.eql(user.status);
            res.body.status.should.be.eql(statusKind.unactivated);
            done();
          });
      })
      .catch(done);
  });

  // 请求不存在的用户
  it('it should fail to get a user when the user is not exists', function (done) {
    let newUserId;
    administrator.createRandomUser()
      .then(({ userId }) => {
        newUserId = userId;
        return administrator.removeUser(userId);
      })
      .then(() => administrator.login())
      .then(() => {
        chai.request(uri)
          .get(url(newUserId))
          .set('Authorization', `Bearer ${administrator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
